

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" href="/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="Blue~u~u~u">
  <meta name="author" content="Blue~u~u~u">
  <meta name="keywords" content="">
  <meta name="description" content="springmvc-day03第一章 拦截器(重点)1. 概念1.1 使用场景1.1.1 生活中坐地铁的场景为了提高乘车效率，在乘客进入站台前统一检票：   1.1.2 程序中的校验登录场景在程序中，使用拦截器在请求到达具体 handler 方法前，统一执行检测。   1.2 拦截器与过滤器的对比1.2.1 相同点三要素相同  拦截(配置拦截路径)：必须先把请求拦住，才能执行后续操作 过滤(根据某">
<meta property="og:type" content="article">
<meta property="og:title" content="springMVC-03">
<meta property="og:url" content="http://www.slx.blue/2021/12/13/springMVC-03/index.html">
<meta property="og:site_name" content="Blue~u~u~u~u">
<meta property="og:description" content="springmvc-day03第一章 拦截器(重点)1. 概念1.1 使用场景1.1.1 生活中坐地铁的场景为了提高乘车效率，在乘客进入站台前统一检票：   1.1.2 程序中的校验登录场景在程序中，使用拦截器在请求到达具体 handler 方法前，统一执行检测。   1.2 拦截器与过滤器的对比1.2.1 相同点三要素相同  拦截(配置拦截路径)：必须先把请求拦住，才能执行后续操作 过滤(根据某">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://www.slx.blue/2021/12/13/springMVC-03/tu_001.png">
<meta property="og:image" content="http://www.slx.blue/2021/12/13/springMVC-03/tu_002.png">
<meta property="og:image" content="http://www.slx.blue/2021/12/13/springMVC-03/tu_003.png">
<meta property="og:image" content="http://www.slx.blue/2021/12/13/springMVC-03/tu_004.png">
<meta property="og:image" content="http://www.slx.blue/2021/12/13/springMVC-03/tu_005.png">
<meta property="og:image" content="http://www.slx.blue/2021/12/13/springMVC-03/tu_006.png">
<meta property="og:image" content="http://www.slx.blue/2021/12/13/springMVC-03/tu_007.png">
<meta property="og:image" content="http://www.slx.blue/2021/12/13/springMVC-03/tu_008.png">
<meta property="og:image" content="http://www.slx.blue/2021/12/13/springMVC-03/tu_009.png">
<meta property="og:image" content="http://www.slx.blue/2021/12/13/springMVC-03/tu_010.png">
<meta property="og:image" content="http://www.slx.blue/2021/12/13/springMVC-03/tu_011.png">
<meta property="og:image" content="http://www.slx.blue/2021/12/13/springMVC-03/tu_012.png">
<meta property="og:image" content="http://www.slx.blue/2021/12/13/springMVC-03/tu_013.png">
<meta property="og:image" content="http://www.slx.blue/2021/12/13/springMVC-03/tu_014.png">
<meta property="article:published_time" content="2021-12-13T11:57:31.000Z">
<meta property="article:modified_time" content="2021-12-13T11:59:17.180Z">
<meta property="article:author" content="Blue~u~u~u">
<meta property="article:tag" content="springMVC">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="http://www.slx.blue/2021/12/13/springMVC-03/tu_001.png">
  
  <title>springMVC-03 - Blue~u~u~u~u</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"www.slx.blue","root":"/","version":"1.8.12","typing":{"enable":true,"typeSpeed":180,"cursorChar":"_","loop":true},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname"}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.4.0"></head>

<script src="https://cdn.jsdelivr.net/npm/jquery/dist/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome/css/font-awesome.min.css"/>
<script src="/live2d-widget/autoload.js"></script>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Blue~u~u</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/links/">
                <i class="iconfont icon-link-fill"></i>
                友链
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/images/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="springMVC-03">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2021-12-13 19:57" pubdate>
        2021年12月13日 晚上
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      21k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      65 分钟
    </span>
  

  
  
    
      <!-- 不蒜子统计文章PV -->
      <span id="busuanzi_container_page_pv" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="busuanzi_value_page_pv"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">springMVC-03</h1>
            
              <p class="note note-info">
                
                  本文最后更新于：6 个月前
                
              </p>
            
            <div class="markdown-body">
              <h1 id="springmvc-day03"><a href="#springmvc-day03" class="headerlink" title="springmvc-day03"></a>springmvc-day03</h1><h2 id="第一章-拦截器-重点"><a href="#第一章-拦截器-重点" class="headerlink" title="第一章 拦截器(重点)"></a>第一章 拦截器(重点)</h2><h3 id="1-概念"><a href="#1-概念" class="headerlink" title="1. 概念"></a>1. 概念</h3><h4 id="1-1-使用场景"><a href="#1-1-使用场景" class="headerlink" title="1.1 使用场景"></a>1.1 使用场景</h4><h5 id="1-1-1-生活中坐地铁的场景"><a href="#1-1-1-生活中坐地铁的场景" class="headerlink" title="1.1.1 生活中坐地铁的场景"></a>1.1.1 生活中坐地铁的场景</h5><p>为了提高乘车效率，在乘客进入站台前统一检票： </p>
<p><img src="http://www.slx.blue/2021/12/13/springMVC-03/tu_001.png" srcset="/img/loading.gif" lazyload></p>
<h5 id="1-1-2-程序中的校验登录场景"><a href="#1-1-2-程序中的校验登录场景" class="headerlink" title="1.1.2 程序中的校验登录场景"></a>1.1.2 程序中的校验登录场景</h5><p>在程序中，使用拦截器在请求到达具体 handler 方法前，统一执行检测。 </p>
<p><img src="http://www.slx.blue/2021/12/13/springMVC-03/tu_002.png" srcset="/img/loading.gif" lazyload></p>
<h4 id="1-2-拦截器与过滤器的对比"><a href="#1-2-拦截器与过滤器的对比" class="headerlink" title="1.2 拦截器与过滤器的对比"></a>1.2 拦截器与过滤器的对比</h4><h5 id="1-2-1-相同点"><a href="#1-2-1-相同点" class="headerlink" title="1.2.1 相同点"></a>1.2.1 相同点</h5><p>三要素相同</p>
<ul>
<li>拦截(配置拦截路径)：必须先把请求拦住，才能执行后续操作</li>
<li>过滤(根据某种规则/业务逻辑进行筛选)：拦截器或过滤器存在的意义就是对请求进行统一处理</li>
<li>放行(满足规则/筛选条件，就让你访问你想访问的资源)：对请求执行了必要操作后，放请求过去，让它访问原本想要访问的资源</li>
</ul>
<h5 id="1-2-2-不同点"><a href="#1-2-2-不同点" class="headerlink" title="1.2.2 不同点"></a>1.2.2 不同点</h5><ul>
<li>工作平台不同<ul>
<li>过滤器工作在 Servlet 容器中</li>
<li>拦截器工作在 SpringMVC 的基础上</li>
</ul>
</li>
<li>拦截的范围<ul>
<li>过滤器：能够拦截到的最大范围是整个 Web 应用</li>
<li>拦截器：能够拦截到的最大范围是整个 SpringMVC 负责的请求(handler方法、view-controller跳转页面)</li>
</ul>
</li>
<li>IOC 容器支持<ul>
<li>过滤器：想得到 IOC 容器需要调用专门的工具方法，是间接的</li>
<li>拦截器：它自己就在 IOC 容器中，所以可以直接从 IOC 容器中装配组件，也就是可以直接得到 IOC 容器的支持</li>
</ul>
</li>
</ul>
<h3 id="2-具体使用"><a href="#2-具体使用" class="headerlink" title="2. 具体使用"></a>2. 具体使用</h3><h4 id="2-1-创建拦截器类"><a href="#2-1-创建拦截器类" class="headerlink" title="2.1 创建拦截器类"></a>2.1 创建拦截器类</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><code class="hljs java"><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Process01Interceptor</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">HandlerInterceptor</span> </span>&#123;<br> <br>    Logger logger = LoggerFactory.getLogger(<span class="hljs-keyword">this</span>.getClass());<br> <br>    <span class="hljs-comment">// 在处理请求的目标 handler 方法前执行</span><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">preHandle</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response, Object handler)</span> <span class="hljs-keyword">throws</span> Exception </span>&#123;<br>        <br>        logger.debug(<span class="hljs-string">&quot;Process01Interceptor preHandle方法&quot;</span>);<br>         <br>        <span class="hljs-comment">// 返回true：放行</span><br>        <span class="hljs-comment">// 返回false：不放行</span><br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">true</span>;<br>    &#125;<br> <br>    <span class="hljs-comment">// 在目标 handler 方法之后，渲染视图之前</span><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">postHandle</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)</span> <span class="hljs-keyword">throws</span> Exception </span>&#123;<br> <br>        logger.debug(<span class="hljs-string">&quot;Process01Interceptor postHandle方法&quot;</span>);<br>        <br>    &#125;<br> <br>    <span class="hljs-comment">// 渲染视图之后执行</span><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">afterCompletion</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)</span> <span class="hljs-keyword">throws</span> Exception </span>&#123;<br>        <br>        logger.debug(<span class="hljs-string">&quot;Process01Interceptor afterCompletion方法&quot;</span>);<br>        <br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><strong>单个拦截器执行顺序</strong>：</p>
<ul>
<li>preHandle() 方法</li>
<li>目标 handler 方法</li>
<li>postHandle() 方法</li>
<li>渲染视图</li>
<li>afterCompletion() 方法</li>
</ul>
<h4 id="2-2-注册拦截器"><a href="#2-2-注册拦截器" class="headerlink" title="2.2 注册拦截器"></a>2.2 注册拦截器</h4><h5 id="2-2-1-默认拦截全部请求"><a href="#2-2-1-默认拦截全部请求" class="headerlink" title="2.2.1 默认拦截全部请求"></a>2.2.1 默认拦截全部请求</h5><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-comment">&lt;!-- 注册拦截器 --&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">mvc:interceptors</span>&gt;</span> <br>    <span class="hljs-comment">&lt;!-- 直接通过内部 bean 配置的拦截器默认拦截全部请求（SpringMVC 范围内） --&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;com.atguigu.interceptor.Demo01Interceptor&quot;</span>/&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">mvc:interceptors</span>&gt;</span><br></code></pre></td></tr></table></figure>

<h5 id="2-2-2-配置拦截路径"><a href="#2-2-2-配置拦截路径" class="headerlink" title="2.2.2 配置拦截路径"></a>2.2.2 配置拦截路径</h5><h6 id="2-2-2-1-精确匹配"><a href="#2-2-2-1-精确匹配" class="headerlink" title="2.2.2.1 精确匹配"></a>2.2.2.1 精确匹配</h6><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-comment">&lt;!-- 具体配置拦截器可以指定拦截的请求地址 --&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">mvc:interceptor</span>&gt;</span><br>    <span class="hljs-comment">&lt;!-- 精确匹配 --&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">mvc:mapping</span> <span class="hljs-attr">path</span>=<span class="hljs-string">&quot;/hello/sayHello&quot;</span>/&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;com.atguigu.interceptor.Demo01Interceptor&quot;</span>/&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">mvc:interceptor</span>&gt;</span><br></code></pre></td></tr></table></figure>

<h6 id="2-2-2-2-模糊匹配：匹配单层路径"><a href="#2-2-2-2-模糊匹配：匹配单层路径" class="headerlink" title="2.2.2.2 模糊匹配：匹配单层路径"></a>2.2.2.2 模糊匹配：匹配单层路径</h6><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">mvc:interceptor</span>&gt;</span><br>    <span class="hljs-comment">&lt;!-- /*匹配路径中的一层 --&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">mvc:mapping</span> <span class="hljs-attr">path</span>=<span class="hljs-string">&quot;/hello/*&quot;</span>/&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;com.atguigu.interceptor.Demo01Interceptor&quot;</span>/&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">mvc:interceptor</span>&gt;</span><br></code></pre></td></tr></table></figure>

<h6 id="2-2-2-3-模糊匹配：匹配多层路径"><a href="#2-2-2-3-模糊匹配：匹配多层路径" class="headerlink" title="2.2.2.3 模糊匹配：匹配多层路径"></a>2.2.2.3 模糊匹配：匹配多层路径</h6><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">mvc:interceptor</span>&gt;</span><br>    <span class="hljs-comment">&lt;!--模糊匹配多级目录--&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">mvc:mapping</span> <span class="hljs-attr">path</span>=<span class="hljs-string">&quot;/hello/**&quot;</span>/&gt;</span><br><br>    <span class="hljs-comment">&lt;!--排除--&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">mvc:exclude-mapping</span> <span class="hljs-attr">path</span>=<span class="hljs-string">&quot;/hello/sayHello&quot;</span>/&gt;</span><br><br>    <span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;com.atguigu.interceptor.Demo01Interceptor&quot;</span>/&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">mvc:interceptor</span>&gt;</span><br></code></pre></td></tr></table></figure>

<h4 id="2-3-多个拦截器执行顺序"><a href="#2-3-多个拦截器执行顺序" class="headerlink" title="2.3 多个拦截器执行顺序"></a>2.3 多个拦截器执行顺序</h4><ul>
<li>preHandle()方法：和配置的顺序一样</li>
<li>目标handler方法</li>
<li>postHandle()方法：和配置的顺序相反</li>
<li>渲染视图</li>
<li>afterCompletion()方法：和配置的顺序相反</li>
</ul>
<h2 id="第二章-类型转换"><a href="#第二章-类型转换" class="headerlink" title="第二章 类型转换"></a>第二章 类型转换</h2><p>SpringMVC 将『把请求参数注入到 POJO 对象』这个操作称为<strong>『数据绑定』</strong>，英文单词是 binding。数据类型的转换和格式化就发生在数据绑定的过程中。 类型转换和格式化是密不可分的两个过程，很多带格式的数据必须明确指定格式之后才可以进行类型转换。最典型的就是日期类型。 </p>
<h3 id="1-自动类型转换"><a href="#1-自动类型转换" class="headerlink" title="1. 自动类型转换"></a>1. 自动类型转换</h3><p>HTTP 协议是一个无类型的协议，我们在服务器端接收到请求参数等形式的数据时，本质上都是字符串类型。请看 javax.servlet.ServletRequest 接口中获取全部请求参数的方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> Map&lt;String, String[]&gt; getParameterMap();<br></code></pre></td></tr></table></figure>

<p>而我们在实体类当中需要的类型是非常丰富的。对此，SpringMVC 对基本数据类型提供了自动的类型转换。例如：请求参数传入“100”字符串，我们实体类中需要的是 Integer 类型，那么 SpringMVC 会自动将字符串转换为 Integer 类型注入实体类。</p>
<h3 id="2-日期和数值类型转换"><a href="#2-日期和数值类型转换" class="headerlink" title="2. 日期和数值类型转换"></a>2. 日期和数值类型转换</h3><h4 id="2-1-通过注解设定数据格式"><a href="#2-1-通过注解设定数据格式" class="headerlink" title="2.1 通过注解设定数据格式"></a>2.1 通过注解设定数据格式</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.atguigu.pojo;<br><br><span class="hljs-keyword">import</span> lombok.AllArgsConstructor;<br><span class="hljs-keyword">import</span> lombok.Data;<br><span class="hljs-keyword">import</span> lombok.NoArgsConstructor;<br><span class="hljs-keyword">import</span> org.springframework.format.annotation.DateTimeFormat;<br><span class="hljs-keyword">import</span> org.springframework.format.annotation.NumberFormat;<br><br><span class="hljs-keyword">import</span> java.util.Date;<br><br><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * 包名:com.atguigu.pojo</span><br><span class="hljs-comment"> *</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@author</span> Leevi</span><br><span class="hljs-comment"> * 日期2021-09-07  11:26</span><br><span class="hljs-comment"> * SpringMVC提供了一些注解，可以让我们进行一些手动类型转换</span><br><span class="hljs-comment"> * 1. DateTimeFormat注解:可以对日期时间类型进行转换</span><br><span class="hljs-comment"> * 2. NumberFormat注解:可以对数值类型进行转换</span><br><span class="hljs-comment"> */</span><br><span class="hljs-meta">@Data</span><br><span class="hljs-meta">@AllArgsConstructor</span><br><span class="hljs-meta">@NoArgsConstructor</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Product</span> </span>&#123;<br>    <span class="hljs-meta">@DateTimeFormat(pattern = &quot;yyyy-MM-dd HH:mm:ss&quot;)</span><br>    <span class="hljs-keyword">private</span> Date productDate;<br><br>    <span class="hljs-meta">@NumberFormat(pattern = &quot;###,###,###.###&quot;)</span><br>    <span class="hljs-keyword">private</span> Double productPrice;<br>&#125;<br><br></code></pre></td></tr></table></figure>

<h4 id="2-2-前端表单"><a href="#2-2-前端表单" class="headerlink" title="2.2 前端表单"></a>2.2 前端表单</h4><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">&quot;en&quot;</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">&quot;UTF-8&quot;</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>首页<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">action</span>=<span class="hljs-string">&quot;/springmvcday0303/hello/saveProduct&quot;</span> <span class="hljs-attr">method</span>=<span class="hljs-string">&quot;post&quot;</span>&gt;</span><br>            生产日期：<span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">&quot;text&quot;</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;productDate&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;1992-10-15 17:15:06&quot;</span> /&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">br</span>/&gt;</span><br>            产品价格：<span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">&quot;text&quot;</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;productPrice&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;111,222,333.444&quot;</span> /&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">br</span>/&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">&quot;submit&quot;</span>&gt;</span>保存<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span><br>        <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span><br></code></pre></td></tr></table></figure>

<h4 id="2-3-handler-方法"><a href="#2-3-handler-方法" class="headerlink" title="2.3 handler 方法"></a>2.3 handler 方法</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@RequestMapping(&quot;/saveProduct&quot;)</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">saveProduct</span><span class="hljs-params">(Product product)</span></span>&#123;<br>    logger.debug(product.toString());<br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;target&quot;</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<h4 id="2-4-转换失败后处理方式"><a href="#2-4-转换失败后处理方式" class="headerlink" title="2.4 转换失败后处理方式"></a>2.4 转换失败后处理方式</h4><h5 id="2-4-1-默认结果"><a href="#2-4-1-默认结果" class="headerlink" title="2.4.1 默认结果"></a>2.4.1 默认结果</h5><p><img src="http://www.slx.blue/2021/12/13/springMVC-03/tu_003.png" srcset="/img/loading.gif" lazyload></p>
<h5 id="2-4-2-BindingResult-接口"><a href="#2-4-2-BindingResult-接口" class="headerlink" title="2.4.2 BindingResult 接口"></a>2.4.2 BindingResult 接口</h5><p>BindingResult 接口和它的父接口 Errors 中定义了很多和数据绑定相关的方法，如果在数据绑定过程中发生了错误，那么通过这个接口类型的对象就可以获取到相关错误信息。 </p>
<p><img src="http://www.slx.blue/2021/12/13/springMVC-03/tu_004.png" srcset="/img/loading.gif" lazyload></p>
<h5 id="2-4-3-重构-handler-方法"><a href="#2-4-3-重构-handler-方法" class="headerlink" title="2.4.3 重构 handler 方法"></a>2.4.3 重构 handler 方法</h5><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@RequestMapping(&quot;/saveProduct&quot;)</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">saveProduct</span><span class="hljs-params">(Product product, BindingResult bindingResult)</span></span>&#123;<br>    <span class="hljs-keyword">if</span> (bindingResult.hasErrors()) &#123;<br>        <span class="hljs-comment">//跳转到错误页面:显示错误数据</span><br>        <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;error&quot;</span>;<br>    &#125;<br>    logger.debug(product.toString());<br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;target&quot;</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<h5 id="2-4-4-在页面上显示错误消息"><a href="#2-4-4-在页面上显示错误消息" class="headerlink" title="2.4.4 在页面上显示错误消息"></a>2.4.4 在页面上显示错误消息</h5><p>页面是error.html，放在Thymeleaf前后缀控制范围之内</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">&quot;en&quot;</span> <span class="hljs-attr">xmlns:th</span>=<span class="hljs-string">&quot;http://www.thymeleaf.org&quot;</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">&quot;UTF-8&quot;</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span><br>        <span class="hljs-comment">&lt;!-- 从请求域获取实体类信息时，属性名是按照类名首字母小写的规则 --&gt;</span><br>        <span class="hljs-comment">&lt;!-- $&#123;注入请求参数的实体类.出问题的字段&#125; --&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">th:errors</span>=<span class="hljs-string">&quot;$&#123;product.productDate&#125;&quot;</span>&gt;</span>这里显示具体错误信息<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">th:errors</span>=<span class="hljs-string">&quot;$&#123;product.productPrice&#125;&quot;</span>&gt;</span>这里显示具体错误信息<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span><br></code></pre></td></tr></table></figure>

<h3 id="3-自定义类型转换器"><a href="#3-自定义类型转换器" class="headerlink" title="3. 自定义类型转换器"></a>3. 自定义类型转换器</h3><h4 id="3-1-创建实体类"><a href="#3-1-创建实体类" class="headerlink" title="3.1 创建实体类"></a>3.1 创建实体类</h4><h5 id="3-1-1-Address"><a href="#3-1-1-Address" class="headerlink" title="3.1.1 Address"></a>3.1.1 Address</h5><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Data</span><br><span class="hljs-meta">@AllArgsConstructor</span><br><span class="hljs-meta">@NoArgsConstructor</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Address</span> </span>&#123;<br>    <span class="hljs-keyword">private</span> String province;<br>    <span class="hljs-keyword">private</span> String city;<br>    <span class="hljs-keyword">private</span> String street;<br>&#125;<br></code></pre></td></tr></table></figure>

<h5 id="3-1-2-Student"><a href="#3-1-2-Student" class="headerlink" title="3.1.2 Student"></a>3.1.2 Student</h5><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Data</span><br><span class="hljs-meta">@AllArgsConstructor</span><br><span class="hljs-meta">@NoArgsConstructor</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Product</span> </span>&#123;<br>    <span class="hljs-meta">@DateTimeFormat(pattern = &quot;yyyy-MM-dd HH:mm:ss&quot;)</span><br>    <span class="hljs-keyword">private</span> Date productDate;<br><br>    <span class="hljs-meta">@NumberFormat(pattern = &quot;###,###,###.###&quot;)</span><br>    <span class="hljs-keyword">private</span> Double productPrice;<br><br>    <span class="hljs-keyword">private</span> Address productAddress;<br>&#125;<br></code></pre></td></tr></table></figure>

<h4 id="3-2-表单"><a href="#3-2-表单" class="headerlink" title="3.2 表单"></a>3.2 表单</h4><p>现在我们希望通过一个文本框输入约定格式的字符串，然后转换为我们需要的类型，所以必须通过自定义类型转换器来实现，否则 SpringMVC 无法识别。 </p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">action</span>=<span class="hljs-string">&quot;/springmvcday0303/hello/saveProduct&quot;</span> <span class="hljs-attr">method</span>=<span class="hljs-string">&quot;post&quot;</span>&gt;</span><br>    生产日期：<span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">&quot;text&quot;</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;productDate&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;1992-10-15 17:15:06&quot;</span> /&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">br</span>/&gt;</span><br>    产品价格：<span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">&quot;text&quot;</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;productPrice&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;111,222,333.444&quot;</span> /&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">br</span>/&gt;</span><br>    生产地: <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">&quot;text&quot;</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;productAddress&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;广东省,深圳市,宝安区航城街道&quot;</span>/&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">&quot;submit&quot;</span>&gt;</span>保存<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span><br></code></pre></td></tr></table></figure>

<h4 id="3-3-handler-方法"><a href="#3-3-handler-方法" class="headerlink" title="3.3 handler 方法"></a>3.3 handler 方法</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@RequestMapping(&quot;/saveProduct&quot;)</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">saveProduct</span><span class="hljs-params">(Product product, BindingResult bindingResult)</span></span>&#123;<br>    <span class="hljs-keyword">if</span> (bindingResult.hasErrors()) &#123;<br>        <span class="hljs-comment">//跳转到错误页面:显示错误数据</span><br>        <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;error&quot;</span>;<br>    &#125;<br>    logger.debug(product.toString());<br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;target&quot;</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>在目前代码的基础上，我们没有提供自定义类型转换器，所以处理请求时看到如下错误日志：</p>
<blockquote>
<p>Field error in object ‘student’ on field ‘address’: rejected value [aaa,bbb,ccc]; codes [typeMismatch.student.address,typeMismatch.address,typeMismatch.com.atguigu.mvc.entity.Address,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [student.address,address]; arguments []; default message [address]]; default message [Failed to convert property value of type ‘java.lang.String’ to required type ‘com.atguigu.mvc.entity.Address’ for property ‘address’; nested exception is java.lang.IllegalStateException: Cannot convert value of type ‘java.lang.String’ to required type ‘com.atguigu.mvc.entity.Address’ for property ‘address’: no matching editors or conversion strategy found]]]</p>
</blockquote>
<p>页面返回 400。</p>
<h4 id="3-4-创建自定义类型转换器类"><a href="#3-4-创建自定义类型转换器类" class="headerlink" title="3.4 创建自定义类型转换器类"></a>3.4 创建自定义类型转换器类</h4><p>实现接口：org.springframework.core.convert.converter.Converter&lt;S,T&gt;</p>
<p>泛型 S：源类型（本例中是 String 类型）</p>
<p>泛型 T：目标类型（本例中是 Address 类型）</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.atguigu.converter;<br><br><span class="hljs-keyword">import</span> com.atguigu.pojo.Address;<br><span class="hljs-keyword">import</span> org.springframework.core.convert.converter.Converter;<br><br><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * 包名:com.atguigu.converter</span><br><span class="hljs-comment"> *</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@author</span> Leevi</span><br><span class="hljs-comment"> * 日期2021-09-07  14:00</span><br><span class="hljs-comment"> * 编写自定义类型转换器:</span><br><span class="hljs-comment"> * 1. 写一个类实现Converter接口</span><br><span class="hljs-comment"> * 2. 重写convert方法进行转换</span><br><span class="hljs-comment"> * 3. 在springmvc的配置文件中配置类型转换器</span><br><span class="hljs-comment"> */</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AddressConverter</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Converter</span>&lt;<span class="hljs-title">String</span> , <span class="hljs-title">Address</span>&gt; </span>&#123;<br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> Address <span class="hljs-title">convert</span><span class="hljs-params">(String source)</span> </span>&#123;<br>        <span class="hljs-comment">//source就是要进行转换的那个字符串</span><br>        <span class="hljs-comment">//1. 解析字符串:获取省、市、街道</span><br>        String[] strs = source.split(<span class="hljs-string">&quot;,&quot;</span>);<br>        <span class="hljs-comment">//2. 创建一个Address对象</span><br>        Address address = <span class="hljs-keyword">new</span> Address();<br>        <span class="hljs-comment">//3. 将省、市、街道设置到Address对象中</span><br>        address.setProvince(strs[<span class="hljs-number">0</span>]);<br>        address.setCity(strs[<span class="hljs-number">1</span>]);<br>        address.setStreet(strs[<span class="hljs-number">2</span>]);<br>        <span class="hljs-keyword">return</span> address;<br>    &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> &lt;U&gt; <span class="hljs-function">Converter&lt;String, U&gt; <span class="hljs-title">andThen</span><span class="hljs-params">(Converter&lt;? <span class="hljs-keyword">super</span> Address, ? extends U&gt; after)</span> </span>&#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>;<br>    &#125;<br>&#125;<br><br></code></pre></td></tr></table></figure>

<h4 id="3-5-在springmvc配置文件中注册类型转换器"><a href="#3-5-在springmvc配置文件中注册类型转换器" class="headerlink" title="3.5 在springmvc配置文件中注册类型转换器"></a>3.5 在springmvc配置文件中注册类型转换器</h4><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-comment">&lt;!-- 在 mvc:annotation-driven 中注册 FormattingConversionServiceFactoryBean --&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">mvc:annotation-driven</span> <span class="hljs-attr">conversion-service</span>=<span class="hljs-string">&quot;formattingConversionService&quot;</span>/&gt;</span><br> <br><span class="hljs-comment">&lt;!-- 在 FormattingConversionServiceFactoryBean 中注册自定义类型转换器 --&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;formattingConversionService&quot;</span></span><br><span class="hljs-tag">      <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;org.springframework.format.support.FormattingConversionServiceFactoryBean&quot;</span>&gt;</span><br>    <span class="hljs-comment">&lt;!-- 在 converters 属性中指定自定义类型转换器 --&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;converters&quot;</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">set</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;com.atguigu.mvc.converter.AddressConverter&quot;</span>/&gt;</span><br>        <span class="hljs-tag">&lt;/<span class="hljs-name">set</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">property</span>&gt;</span><br> <br><span class="hljs-tag">&lt;/<span class="hljs-name">bean</span>&gt;</span><br></code></pre></td></tr></table></figure>

<h2 id="第三章-数据校验-重要"><a href="#第三章-数据校验-重要" class="headerlink" title="第三章 数据校验(重要)"></a>第三章 数据校验(重要)</h2><p>在 Web 应用三层架构体系中，表述层负责接收浏览器提交的数据，业务逻辑层负责数据的处理。为了能够让业务逻辑层基于正确的数据进行处理，我们需要在表述层对数据进行检查，将错误的数据隔绝在业务逻辑层之外。 </p>
<h3 id="1-数据校验概述"><a href="#1-数据校验概述" class="headerlink" title="1. 数据校验概述"></a>1. 数据校验概述</h3><p>JSR 303 是 Java 为 Bean 数据合法性校验提供的标准框架，它已经包含在 JavaEE 6.0 标准中。JSR 303 通过在 Bean 属性上标注类似于 @NotNull、@Max 等标准的注解指定校验规则，并通过标准的验证接口对Bean进行验证。 </p>
<table>
<thead>
<tr>
<th>注解</th>
<th>规则</th>
</tr>
</thead>
<tbody><tr>
<td>@Null</td>
<td>标注值必须为 null</td>
</tr>
<tr>
<td>@NotNull</td>
<td>标注值不可为 null</td>
</tr>
<tr>
<td>@AssertTrue</td>
<td>标注值必须为 true</td>
</tr>
<tr>
<td>@AssertFalse</td>
<td>标注值必须为 false</td>
</tr>
<tr>
<td>@Min(value)</td>
<td>标注值必须大于或等于 value</td>
</tr>
<tr>
<td>@Max(value)</td>
<td>标注值必须小于或等于 value</td>
</tr>
<tr>
<td>@DecimalMin(value)</td>
<td>标注值必须大于或等于 value</td>
</tr>
<tr>
<td>@DecimalMax(value)</td>
<td>标注值必须小于或等于 value</td>
</tr>
<tr>
<td>@Size(max,min)</td>
<td>标注值大小必须在 max 和 min 限定的范围内</td>
</tr>
<tr>
<td>@Digits(integer,fratction)</td>
<td>标注值值必须是一个数字，且必须在可接受的范围内</td>
</tr>
<tr>
<td>@Past</td>
<td>标注值只能用于日期型，且必须是过去的日期</td>
</tr>
<tr>
<td>@Future</td>
<td>标注值只能用于日期型，且必须是将来的日期</td>
</tr>
<tr>
<td>@Pattern(value)</td>
<td>标注值必须符合指定的正则表达式</td>
</tr>
</tbody></table>
<p>JSR 303 只是一套标准，需要提供其实现才可以使用。Hibernate Validator 是 JSR 303 的一个参考实现，除支持所有标准的校验注解外，它还支持以下的扩展注解： </p>
<table>
<thead>
<tr>
<th>注解</th>
<th>规则</th>
</tr>
</thead>
<tbody><tr>
<td>@Email</td>
<td>标注值必须是格式正确的 Email 地址</td>
</tr>
<tr>
<td>@Length</td>
<td>标注值字符串大小必须在指定的范围内</td>
</tr>
<tr>
<td>@NotEmpty</td>
<td>标注值字符串不能是空字符串</td>
</tr>
<tr>
<td>@Range</td>
<td>标注值必须在指定的范围内</td>
</tr>
</tbody></table>
<p>Spring 4.0 版本已经拥有自己独立的数据校验框架，同时支持 JSR 303 标准的校验框架。Spring 在进行数据绑定时，可同时调用校验框架完成数据校验工作。在SpringMVC 中，可直接通过注解驱动 mvc:annotation-driven 的方式进行数据校验。Spring 的 LocalValidatorFactoryBean 既实现了 Spring 的 Validator 接口，也实现了 JSR 303 的 Validator 接口。只要在Spring容器中定义了一个LocalValidatorFactoryBean，即可将其注入到需要数据校验的 Bean中。Spring本身并没有提供JSR 303的实现，所以必须将JSR 303的实现者的jar包放到类路径下。</p>
<p>配置 mvc:annotation-driven 后，SpringMVC 会默认装配好一个 LocalValidatorFactoryBean，通过<strong>在处理方法的入参上标注 @Validated 注解</strong>即可让 SpringMVC 在完成数据绑定后执行数据校验的工作。</p>
<h3 id="2-具体操作"><a href="#2-具体操作" class="headerlink" title="2. 具体操作"></a>2. 具体操作</h3><p>前提:1.  springmvc环境   2. Tomcat8及以上版本</p>
<h4 id="2-1-引入依赖"><a href="#2-1-引入依赖" class="headerlink" title="2.1 引入依赖"></a>2.1 引入依赖</h4><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-comment">&lt;!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator --&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.hibernate.validator<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>hibernate-validator<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>6.2.0.Final<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br><span class="hljs-comment">&lt;!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator-annotation-processor --&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.hibernate.validator<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>hibernate-validator-annotation-processor<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>6.2.0.Final<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br></code></pre></td></tr></table></figure>

<h4 id="2-2-应用校验规则"><a href="#2-2-应用校验规则" class="headerlink" title="2.2 应用校验规则"></a>2.2 应用校验规则</h4><h5 id="2-2-1-给要进行校验的字段添加上校验规则注解"><a href="#2-2-1-给要进行校验的字段添加上校验规则注解" class="headerlink" title="2.2.1 给要进行校验的字段添加上校验规则注解"></a>2.2.1 给要进行校验的字段添加上校验规则注解</h5><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Data</span><br><span class="hljs-meta">@AllArgsConstructor</span><br><span class="hljs-meta">@NoArgsConstructor</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">President</span> </span>&#123;<br>    <span class="hljs-comment">// 字符串长度：[3,6]</span><br>    <span class="hljs-meta">@Size(min = 3, max = 6)</span><br>    <span class="hljs-keyword">private</span> String username;<br>    <span class="hljs-comment">// 字符串必须满足Email格式</span><br>    <span class="hljs-meta">@Email</span><br>    <span class="hljs-keyword">private</span> String email;<br><br>&#125;<br></code></pre></td></tr></table></figure>

<h5 id="2-2-2-给handler方法的形参加上Validated"><a href="#2-2-2-给handler方法的形参加上Validated" class="headerlink" title="2.2.2 给handler方法的形参加上Validated"></a>2.2.2 给handler方法的形参加上Validated</h5><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@RequestMapping(&quot;/savePresident&quot;)</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">savePresident</span><span class="hljs-params">(<span class="hljs-meta">@Validated</span> President president)</span></span>&#123;<br>    logger.debug(president.toString());<br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;target&quot;</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<h4 id="2-3-校验失败效果"><a href="#2-3-校验失败效果" class="headerlink" title="2.3 校验失败效果"></a>2.3 校验失败效果</h4><p>日志：</p>
<blockquote>
<p>Field error in object ‘president’ on field ‘email’: rejected value [aa]; codes [Email.president.email,Email.email,Email.java.lang.String,Email]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [president.email,email]; arguments []; default message [email],[Ljavax.validation.constraints.Pattern$Flag;@4a6addb7,.*]; default message [不是一个合法的电子邮件地址] Field error in object ‘president’ on field ‘email’: rejected value [aa]; codes [Size.president.email,Size.email,Size.java.lang.String,Size]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [president.email,email]; arguments []; default message [email],6,3]; default message [个数必须在3和6之间]]]</p>
</blockquote>
<p>同时页面返回 400。</p>
<h4 id="2-4-显示友好的错误提示"><a href="#2-4-显示友好的错误提示" class="headerlink" title="2.4 显示友好的错误提示"></a>2.4 显示友好的错误提示</h4><h5 id="2-4-1-重构-handler-方法"><a href="#2-4-1-重构-handler-方法" class="headerlink" title="2.4.1 重构 handler 方法"></a>2.4.1 重构 handler 方法</h5><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@RequestMapping(&quot;/save/president&quot;)</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">savePresident</span><span class="hljs-params">(</span></span><br><span class="hljs-params"><span class="hljs-function">        // 在实体类参数和 BindingResult 之间不能有任何其他参数</span></span><br><span class="hljs-params"><span class="hljs-function">        <span class="hljs-meta">@Validated</span> President president, BindingResult bindingResult)</span> </span>&#123;<br> <br>    <span class="hljs-keyword">if</span> (bindingResult.hasErrors()) &#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;error&quot;</span>;<br>    &#125;<br>     <br>    logger.debug(president.getEmail());<br> <br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;target&quot;</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<h5 id="2-4-2-准备错误信息页面"><a href="#2-4-2-准备错误信息页面" class="headerlink" title="2.4.2 准备错误信息页面"></a>2.4.2 准备错误信息页面</h5><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>系统信息<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span><br><span class="hljs-comment">&lt;!-- 从请求域获取实体类信息时，属性名是按照类名首字母小写的规则 --&gt;</span><br><span class="hljs-comment">&lt;!-- $&#123;注入请求参数的实体类.出问题的字段&#125; --&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">th:errors</span>=<span class="hljs-string">&quot;$&#123;president.email&#125;&quot;</span>&gt;</span>这里显示系统提示消息<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span><br></code></pre></td></tr></table></figure>

<h2 id="第四章-异常映射"><a href="#第四章-异常映射" class="headerlink" title="第四章 异常映射"></a>第四章 异常映射</h2><h3 id="1-为什么需要异常映射"><a href="#1-为什么需要异常映射" class="headerlink" title="1. 为什么需要异常映射"></a>1. 为什么需要异常映射</h3><p>一个项目中会包含很多个模块，各个模块需要分工完成。如果张三负责的模块按照 A 方案处理异常，李四负责的模块按照 B 方法处理异常……各个模块处理异常的思路、代码、命名细节都不一样，那么就会让整个项目非常混乱。 </p>
<p>异常映射可以将异常类型和某个具体的视图关联起来，建立映射关系。好处是可以通过 SpringMVC 框架来帮助我们管理异常。</p>
<ul>
<li>声明式管理异常：在配置文件中指定异常类型和视图之间的对应关系。在配置文件或注解类中统一管理。</li>
<li>编程式管理异常：需要我们自己手动 try … catch … 捕获异常，然后再手动跳转到某个页面。</li>
</ul>
<h3 id="2-异常映射的优势"><a href="#2-异常映射的优势" class="headerlink" title="2. 异常映射的优势"></a>2. 异常映射的优势</h3><ul>
<li>使用声明式代替编程式来实现异常管理<ul>
<li>让异常控制和核心业务解耦，二者各自维护，结构性更好</li>
</ul>
</li>
<li>整个项目层面使用同一套规则来管理异常<ul>
<li>整个项目代码风格更加统一、简洁</li>
<li>便于团队成员之间的彼此协作</li>
</ul>
</li>
</ul>
<h3 id="3-基于-XML-的异常映射"><a href="#3-基于-XML-的异常映射" class="headerlink" title="3. 基于 XML 的异常映射"></a>3. 基于 XML 的异常映射</h3><h4 id="3-1-XML配置"><a href="#3-1-XML配置" class="headerlink" title="3.1 XML配置"></a>3.1 XML配置</h4><p>SpringMVC 会根据异常映射信息，在捕获到指定异常对象后，将异常对象存入请求域，然后转发到和异常类型关联的视图。</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-comment">&lt;!--配置异常处理--&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;exceptionResolver&quot;</span></span><br><span class="hljs-tag">      <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;org.springframework.web.servlet.handler.SimpleMappingExceptionResolver&quot;</span>&gt;</span><br><br>    <span class="hljs-comment">&lt;!-- 配置异常映射关系 --&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;exceptionMappings&quot;</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">props</span>&gt;</span><br>            <span class="hljs-comment">&lt;!-- key属性：指定异常类型 --&gt;</span><br>            <span class="hljs-comment">&lt;!-- 文本标签体：和异常类型对应的逻辑视图 --&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">prop</span> <span class="hljs-attr">key</span>=<span class="hljs-string">&quot;java.lang.ArithmeticException&quot;</span>&gt;</span>error-arith<span class="hljs-tag">&lt;/<span class="hljs-name">prop</span>&gt;</span><br><br>            <span class="hljs-tag">&lt;<span class="hljs-name">prop</span> <span class="hljs-attr">key</span>=<span class="hljs-string">&quot;java.lang.ClassNotFoundException&quot;</span>&gt;</span>error-class<span class="hljs-tag">&lt;/<span class="hljs-name">prop</span>&gt;</span><br><br>            <span class="hljs-tag">&lt;<span class="hljs-name">prop</span> <span class="hljs-attr">key</span>=<span class="hljs-string">&quot;java.lang.RuntimeException&quot;</span>&gt;</span>error-runtime<span class="hljs-tag">&lt;/<span class="hljs-name">prop</span>&gt;</span><br>        <span class="hljs-tag">&lt;/<span class="hljs-name">props</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">property</span>&gt;</span><br>    <span class="hljs-comment">&lt;!--</span><br><span class="hljs-comment">            SimpleMappingExceptionResolver在处理异常的时候，会将异常对象存储到请求域中</span><br><span class="hljs-comment">            我们下面的配置，就是用于指定将异常对象存储进请求域的时候，使用的是key叫什么</span><br><span class="hljs-comment">        --&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;exceptionAttribute&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;atguiguException&quot;</span>/&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">bean</span>&gt;</span><br></code></pre></td></tr></table></figure>

<h4 id="3-2-异常范围"><a href="#3-2-异常范围" class="headerlink" title="3.2 异常范围"></a>3.2 异常范围</h4><p>如果在配置文件中，发现有多个匹配的异常类型，那么 SpringMVC 会采纳范围上最接近的异常映射关系。 </p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">prop</span> <span class="hljs-attr">key</span>=<span class="hljs-string">&quot;java.lang.ArithmeticException&quot;</span>&gt;</span>error-arith<span class="hljs-tag">&lt;/<span class="hljs-name">prop</span>&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">prop</span> <span class="hljs-attr">key</span>=<span class="hljs-string">&quot;java.lang.RuntimeException&quot;</span>&gt;</span>error-runtime<span class="hljs-tag">&lt;/<span class="hljs-name">prop</span>&gt;</span><br></code></pre></td></tr></table></figure>

<h3 id="4-基于注解的异常映射"><a href="#4-基于注解的异常映射" class="headerlink" title="4. 基于注解的异常映射"></a>4. 基于注解的异常映射</h3><h4 id="4-1-创建异常处理器类"><a href="#4-1-创建异常处理器类" class="headerlink" title="4.1 创建异常处理器类"></a>4.1 创建异常处理器类</h4><p><img src="http://www.slx.blue/2021/12/13/springMVC-03/tu_005.png" srcset="/img/loading.gif" lazyload></p>
<h4 id="4-2-异常处理器对象加入-IOC-容器"><a href="#4-2-异常处理器对象加入-IOC-容器" class="headerlink" title="4.2 异常处理器对象加入 IOC 容器"></a>4.2 异常处理器对象加入 IOC 容器</h4><h5 id="4-2-1-包扫描"><a href="#4-2-1-包扫描" class="headerlink" title="4.2.1 包扫描"></a>4.2.1 包扫描</h5><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-comment">&lt;!--1.包扫描--&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">context:component-scan</span> <span class="hljs-attr">base-package</span>=<span class="hljs-string">&quot;com.atguigu&quot;</span>/&gt;</span><br></code></pre></td></tr></table></figure>

<h5 id="4-2-2-给异常处理器类标记注解"><a href="#4-2-2-给异常处理器类标记注解" class="headerlink" title="4.2.2 给异常处理器类标记注解"></a>4.2.2 给异常处理器类标记注解</h5><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 异常处理器类需要使用 @ControllerAdvice 注解标记</span><br><span class="hljs-meta">@ControllerAdvice</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyExceptionHandler</span> </span>&#123;<br>    <br>&#125;<br></code></pre></td></tr></table></figure>

<h4 id="4-3-声明处理异常的方法"><a href="#4-3-声明处理异常的方法" class="headerlink" title="4.3 声明处理异常的方法"></a>4.3 声明处理异常的方法</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// @ExceptionHandler注解：标记异常处理方法</span><br><span class="hljs-comment">// value属性：指定匹配的异常类型</span><br><span class="hljs-comment">// 异常类型的形参：SpringMVC 捕获到的异常对象</span><br><span class="hljs-meta">@ExceptionHandler(value = NullPointerException.class)</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">resolveNullPointerException</span><span class="hljs-params">(Exception e, Model model)</span> </span>&#123;<br> <br>    <span class="hljs-comment">// 我们可以自己手动将异常对象存入模型</span><br>    model.addAttribute(<span class="hljs-string">&quot;atguiguException&quot;</span>, e);<br> <br>    <span class="hljs-comment">// 返回逻辑视图名称</span><br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;error-nullpointer&quot;</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>当同一个异常类型在基于 XML 和注解的配置中都能够找到对应的映射，那么以注解为准。 </p>
<h3 id="5-区分请求类型"><a href="#5-区分请求类型" class="headerlink" title="5. 区分请求类型"></a>5. 区分请求类型</h3><h4 id="5-1-为什么要区分请求类型"><a href="#5-1-为什么要区分请求类型" class="headerlink" title="5.1 为什么要区分请求类型"></a>5.1 为什么要区分请求类型</h4><p>异常处理机制和拦截器机制都面临这样的问题： </p>
<p><img src="http://www.slx.blue/2021/12/13/springMVC-03/tu_006.png" srcset="/img/loading.gif" lazyload></p>
<h4 id="5-2-判断依据"><a href="#5-2-判断依据" class="headerlink" title="5.2 判断依据"></a>5.2 判断依据</h4><p>查看请求消息头中是否包含 Ajax 请求独有的特征：</p>
<ul>
<li>Accept 请求消息头：包含 application/json</li>
<li>X-Requested-With 请求消息头：包含 XMLHttpRequest</li>
</ul>
<p>两个条件满足一个即可。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 判断请求类型，如果返回true就是同步请求，返回false就是异步请求</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> request</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@return</span></span><br><span class="hljs-comment">     */</span><br><span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">judgeRequestType</span><span class="hljs-params">(HttpServletRequest request)</span> </span>&#123;<br>    <span class="hljs-comment">//加入代码判断当前请求是同步请求还是异步请求:通过accept或者X-Requested-With</span><br>    String acceptHeader = request.getHeader(<span class="hljs-string">&quot;Accept&quot;</span>);<br>    String xRequestHeader = request.getHeader(<span class="hljs-string">&quot;X-Requested-With&quot;</span>);<br><br>    <span class="hljs-keyword">return</span> !((acceptHeader != <span class="hljs-keyword">null</span> &amp;&amp; acceptHeader.contains(<span class="hljs-string">&quot;application/json&quot;</span>)) ||<br>             (xRequestHeader != <span class="hljs-keyword">null</span> &amp;&amp; xRequestHeader.equals(<span class="hljs-string">&quot;XMLHttpRequest&quot;</span>)));<br>&#125;<br></code></pre></td></tr></table></figure>

<h4 id="5-3-重构异常处理器兼容两种请求的处理方法"><a href="#5-3-重构异常处理器兼容两种请求的处理方法" class="headerlink" title="5.3 重构异常处理器兼容两种请求的处理方法"></a>5.3 重构异常处理器兼容两种请求的处理方法</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@ExceptionHandler(value = Exception.class)</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">resolveNullPointerException</span><span class="hljs-params">(HttpServletResponse response,</span></span><br><span class="hljs-params"><span class="hljs-function">                                          HttpServletRequest request,</span></span><br><span class="hljs-params"><span class="hljs-function">                                          Exception e, Model model)</span> <span class="hljs-keyword">throws</span> IOException </span>&#123;<br>    <span class="hljs-comment">//这个方法处理空指针异常</span><br>    <span class="hljs-keyword">if</span>(!judgeRequestType(request))&#123;<br>        <span class="hljs-comment">//说明当前是异步请求:使用response向客户端响应异常信息</span><br>        response.getWriter().write(e.getMessage());<br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>;<br>    &#125;<br>    <span class="hljs-comment">//要获取异常信息，并且将异常信息存储到请求域</span><br>    model.addAttribute(<span class="hljs-string">&quot;atguiguException&quot;</span>,e);<br>    <span class="hljs-comment">//这个方法返回:异常处理页面的逻辑视图</span><br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;error&quot;</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<h2 id="第五章-文件上传-重要"><a href="#第五章-文件上传-重要" class="headerlink" title="第五章 文件上传(重要)"></a>第五章 文件上传(重要)</h2><h3 id="1-前端表单"><a href="#1-前端表单" class="headerlink" title="1. 前端表单"></a>1. 前端表单</h3><p>需要满足的要求:</p>
<ul>
<li>第一点：请求方式必须是 POST</li>
<li>第二点：请求体的编码方式必须是 multipart/form-data（通过 form 标签的 enctype 属性设置）</li>
<li>第三点：使用 input 标签、type 属性设置为 file 来生成文件上传框</li>
</ul>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">th:action</span>=<span class="hljs-string">&quot;@&#123;/atguigu/upload&#125;&quot;</span> <span class="hljs-attr">method</span>=<span class="hljs-string">&quot;post&quot;</span> <span class="hljs-attr">enctype</span>=<span class="hljs-string">&quot;multipart/form-data&quot;</span>&gt;</span><br>    <br>    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">&quot;file&quot;</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;picture&quot;</span> /&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">&quot;submit&quot;</span>&gt;</span>上传头像<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span><br>     <br><span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span><br></code></pre></td></tr></table></figure>

<h3 id="2-SpringMVC-环境"><a href="#2-SpringMVC-环境" class="headerlink" title="2. SpringMVC 环境"></a>2. SpringMVC 环境</h3><h4 id="2-1-引入依赖-1"><a href="#2-1-引入依赖-1" class="headerlink" title="2.1 引入依赖"></a>2.1 引入依赖</h4><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-comment">&lt;!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>commons-fileupload<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>commons-fileupload<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>1.3.1<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br></code></pre></td></tr></table></figure>

<h4 id="2-2-配置"><a href="#2-2-配置" class="headerlink" title="2.2 配置"></a>2.2 配置</h4><p>在 SpringMVC 的配置文件中加入 multipart 类型数据的解析器： </p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;multipartResolver&quot;</span> </span><br><span class="hljs-tag">      <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;org.springframework.web.multipart.commons.CommonsMultipartResolver&quot;</span>&gt;</span><br>    <br>    <span class="hljs-comment">&lt;!-- 由于上传文件的表单请求体编码方式是 multipart/form-data 格式，所以要在解析器中指定字符集 --&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;defaultEncoding&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;UTF-8&quot;</span>/&gt;</span><br>    <br><span class="hljs-tag">&lt;/<span class="hljs-name">bean</span>&gt;</span><br></code></pre></td></tr></table></figure>

<h3 id="3-handler-方法接收数据"><a href="#3-handler-方法接收数据" class="headerlink" title="3. handler 方法接收数据"></a>3. handler 方法接收数据</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@RequestMapping(&quot;/simple/upload&quot;)</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">doUpload</span><span class="hljs-params">(</span></span><br><span class="hljs-params"><span class="hljs-function"> </span></span><br><span class="hljs-params"><span class="hljs-function">        // 表单提交的数据仍然是请求参数，所以使用 <span class="hljs-meta">@RequestParam</span> 注解接收</span></span><br><span class="hljs-params"><span class="hljs-function">        <span class="hljs-meta">@RequestParam(&quot;nickName&quot;)</span> String nickName,</span></span><br><span class="hljs-params"><span class="hljs-function"> </span></span><br><span class="hljs-params"><span class="hljs-function">        // 对于上传的文件使用 MultipartFile 类型接收其相关数据</span></span><br><span class="hljs-params"><span class="hljs-function">        <span class="hljs-meta">@RequestParam(&quot;picture&quot;)</span> MultipartFile picture</span></span><br><span class="hljs-params"><span class="hljs-function">        )</span> <span class="hljs-keyword">throws</span> IOException </span>&#123;<br> <br>    String inputName = picture.getName();<br>    logger.debug(<span class="hljs-string">&quot;文件上传表单项的 name 属性值：&quot;</span> + inputName);<br> <br>    <span class="hljs-comment">// 获取这个数据通常都是为了获取文件本身的扩展名</span><br>    String originalFilename = picture.getOriginalFilename();<br>    logger.debug(<span class="hljs-string">&quot;文件在用户本地原始的文件名：&quot;</span> + originalFilename);<br> <br>    String contentType = picture.getContentType();<br>    logger.debug(<span class="hljs-string">&quot;文件的内容类型：&quot;</span> + contentType);<br> <br>    <span class="hljs-keyword">boolean</span> empty = picture.isEmpty();<br>    logger.debug(<span class="hljs-string">&quot;文件是否为空：&quot;</span> + empty);<br> <br>    <span class="hljs-keyword">long</span> size = picture.getSize();<br>    logger.debug(<span class="hljs-string">&quot;文件大小：&quot;</span> + size);<br> <br>    <span class="hljs-keyword">byte</span>[] bytes = picture.getBytes();<br>    logger.debug(<span class="hljs-string">&quot;文件二进制数据的字节数组：&quot;</span> + Arrays.asList(bytes));<br> <br>    InputStream inputStream = picture.getInputStream();<br>    logger.debug(<span class="hljs-string">&quot;读取文件数据的输入流对象：&quot;</span> + inputStream);<br> <br>    Resource resource = picture.getResource();<br>    logger.debug(<span class="hljs-string">&quot;代表当前 MultiPartFile 对象的资源对象&quot;</span> + resource);<br> <br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;target&quot;</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="4-MultipartFile接口介绍"><a href="#4-MultipartFile接口介绍" class="headerlink" title="4. MultipartFile接口介绍"></a>4. MultipartFile接口介绍</h3><p><img src="http://www.slx.blue/2021/12/13/springMVC-03/tu_007.png" srcset="/img/loading.gif" lazyload></p>
<h3 id="5-文件转存"><a href="#5-文件转存" class="headerlink" title="5. 文件转存"></a>5. 文件转存</h3><h4 id="5-1-底层原理"><a href="#5-1-底层原理" class="headerlink" title="5.1 底层原理"></a>5.1 底层原理</h4><p><img src="http://www.slx.blue/2021/12/13/springMVC-03/tu_008.png" srcset="/img/loading.gif" lazyload></p>
<h4 id="5-2-三种去向"><a href="#5-2-三种去向" class="headerlink" title="5.2 三种去向"></a>5.2 三种去向</h4><h5 id="5-2-1-本地转存"><a href="#5-2-1-本地转存" class="headerlink" title="5.2.1 本地转存"></a>5.2.1 本地转存</h5><p><img src="http://www.slx.blue/2021/12/13/springMVC-03/tu_009.png" srcset="/img/loading.gif" lazyload></p>
<h6 id="5-2-1-1-创建保存文件的目录"><a href="#5-2-1-1-创建保存文件的目录" class="headerlink" title="5.2.1.1  创建保存文件的目录"></a>5.2.1.1  <strong>创建保存文件的目录</strong></h6><p><img src="http://www.slx.blue/2021/12/13/springMVC-03/tu_010.png" srcset="/img/loading.gif" lazyload></p>
<p>这个目录如果是空目录，那么服务器部署运行时很容易会忽略这个目录。为了避免这个问题，在这个目录下随便创建一个文件，随便写点内容即可。 </p>
<h6 id="5-2-1-2-编写转存代码"><a href="#5-2-1-2-编写转存代码" class="headerlink" title="5.2.1.2  编写转存代码"></a>5.2.1.2  <strong>编写转存代码</strong></h6><p>下面是负责处理文件上传请求的 handler 方法的转存部分： </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Autowired</span><br><span class="hljs-keyword">private</span> ServletContext servletContext;<br>Logger logger = LoggerFactory.getLogger(<span class="hljs-keyword">this</span>.getClass());<br><span class="hljs-meta">@RequestMapping(&quot;/upload&quot;)</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">upload</span><span class="hljs-params">(<span class="hljs-meta">@RequestParam(&quot;nickname&quot;)</span> String nickname,<span class="hljs-meta">@RequestParam(&quot;picture&quot;)</span> MultipartFile multipartFile)</span> <span class="hljs-keyword">throws</span> IOException </span>&#123;<br>    <span class="hljs-comment">//获取请求参数(除了文件之外)，还是和以前一样的方式获取</span><br>    logger.debug(nickname);<br>    <span class="hljs-comment">//multipartFile对象就表示客户端上传的文件</span><br>    <span class="hljs-comment">//1. 指定转存的目录路径:动态获取部署的目录路径</span><br>    String dirPath = servletContext.getRealPath(<span class="hljs-string">&quot;head-picture&quot;</span>);<br><br>    <span class="hljs-comment">//2. 获取文件名:在获取到原文件的文件名之后，将其文件名改成一个唯一的名字，这样就能保证不会出现上传文件同名的情况</span><br>    String UUIDName = UUID.randomUUID().toString().replace(<span class="hljs-string">&quot;-&quot;</span>,<span class="hljs-string">&quot;&quot;</span>);<br>    <span class="hljs-comment">//获取文件名的后缀</span><br>    String originalFilename = multipartFile.getOriginalFilename();<br>    String suffix = originalFilename.substring(originalFilename.lastIndexOf(<span class="hljs-string">&quot;.&quot;</span>));<br><br>    <span class="hljs-comment">//唯一的文件名就是UUIDName拼接后缀</span><br>    String fileName = UUIDName + suffix;<br>    <span class="hljs-comment">//要将该文件转存到目录中</span><br>    multipartFile.transferTo(<span class="hljs-keyword">new</span> File(dirPath+<span class="hljs-string">&quot;/&quot;</span>+fileName));<br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;target&quot;</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<h6 id="5-2-1-3-缺陷"><a href="#5-2-1-3-缺陷" class="headerlink" title="5.2.1.3 缺陷"></a>5.2.1.3 缺陷</h6><ul>
<li>Web 应用重新部署时通常都会清理旧的构建结果，此时用户以前上传的文件会被删除，导致数据丢失。</li>
<li>项目运行很长时间后，会导致上传的文件积累非常多，体积非常大，从而拖慢 Tomcat 运行速度。</li>
<li>当服务器以集群模式运行时，文件上传到集群中的某一个实例，其他实例中没有这个文件，就会造成数据不一致。</li>
<li>不支持动态扩容，一旦系统增加了新的硬盘或新的服务器实例，那么上传、下载时使用的路径都需要跟着变化，导致 Java 代码需要重新编写、重新编译，进而导致整个项目重新部署。</li>
</ul>
<p><img src="http://www.slx.blue/2021/12/13/springMVC-03/tu_011.png" srcset="/img/loading.gif" lazyload></p>
<h5 id="5-2-2-文件服务器"><a href="#5-2-2-文件服务器" class="headerlink" title="5.2.2 文件服务器"></a>5.2.2 文件服务器</h5><p><img src="http://www.slx.blue/2021/12/13/springMVC-03/tu_012.png" srcset="/img/loading.gif" lazyload></p>
<h6 id="5-2-2-1-优势"><a href="#5-2-2-1-优势" class="headerlink" title="5.2.2.1 优势"></a>5.2.2.1 优势</h6><ul>
<li>不受 Web 应用重新部署影响</li>
<li>在应用服务器集群环境下不会导致数据不一致</li>
<li>针对文件读写进行专门的优化，性能有保障</li>
<li>能够实现动态扩容</li>
</ul>
<p><img src="http://www.slx.blue/2021/12/13/springMVC-03/tu_013.png" srcset="/img/loading.gif" lazyload></p>
<h6 id="5-2-2-2-常见的文件服务器类型"><a href="#5-2-2-2-常见的文件服务器类型" class="headerlink" title="5.2.2.2 常见的文件服务器类型"></a>5.2.2.2 常见的文件服务器类型</h6><ul>
<li>第三方平台：<ul>
<li>阿里的 OSS 对象存储服务</li>
<li>七牛云</li>
</ul>
</li>
<li>自己搭建服务器：FastDFS等</li>
</ul>
<h5 id="5-2-3-上传到其他模块-了解"><a href="#5-2-3-上传到其他模块-了解" class="headerlink" title="5.2.3 上传到其他模块(了解)"></a>5.2.3 上传到其他模块(了解)</h5><p>这种情况肯定出现在分布式架构中，常规业务功能不会这么做，采用这个方案的一定的特殊情况。 </p>
<p><img src="http://www.slx.blue/2021/12/13/springMVC-03/tu_014.png" srcset="/img/loading.gif" lazyload></p>
<h2 id="第六章-文件下载-了解"><a href="#第六章-文件下载-了解" class="headerlink" title="第六章 文件下载(了解)"></a>第六章 文件下载(了解)</h2><h3 id="1-原始形态"><a href="#1-原始形态" class="headerlink" title="1. 原始形态"></a>1. 原始形态</h3><p>使用链接地址指向要下载的文件。此时浏览器会尽可能解析对应的文件，只要是能够在浏览器窗口展示的，就都会直接显示，而不是提示下载。 </p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">&quot;download/hello.atguigu&quot;</span>&gt;</span>下载<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">br</span>/&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">&quot;download/tank.jpg&quot;</span>&gt;</span>下载<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">br</span>/&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">&quot;download/chapter04.zip&quot;</span>&gt;</span>下载<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">br</span>/&gt;</span><br></code></pre></td></tr></table></figure>

<p>上面例子中，只有 chapter04.zip 文件是直接提示下载的，其他两个都是直接显示。 </p>
<h3 id="2-明确要求浏览器提示下载"><a href="#2-明确要求浏览器提示下载" class="headerlink" title="2. 明确要求浏览器提示下载"></a>2. 明确要求浏览器提示下载</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Autowired</span><br><span class="hljs-keyword">private</span> ServletContext servletContext;<br><span class="hljs-meta">@RequestMapping(&quot;/download&quot;)</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> ResponseEntity <span class="hljs-title">download</span><span class="hljs-params">(<span class="hljs-meta">@RequestParam(&quot;fileName&quot;)</span> String fileName)</span> <span class="hljs-keyword">throws</span> IOException </span>&#123;<br>    <span class="hljs-comment">//用来下载文件:</span><br>    <span class="hljs-comment">//1. 使用输入流读取要下载的文件</span><br>    <span class="hljs-comment">//1.1 获取要下载的文件路径</span><br>    String downloadPath = servletContext.getRealPath(<span class="hljs-string">&quot;download/&quot;</span>+fileName);<br>    <span class="hljs-comment">//1.2 读取要下载的文件</span><br>    FileInputStream fileInputStream = <span class="hljs-keyword">new</span> FileInputStream(downloadPath);<br>    <span class="hljs-keyword">int</span> len = fileInputStream.available();<br>    <span class="hljs-keyword">byte</span>[] buffer = <span class="hljs-keyword">new</span> <span class="hljs-keyword">byte</span>[len];<br>    fileInputStream.read(buffer);<br><br>    <span class="hljs-comment">//2. 将要下载的文件输出到浏览器:使用响应</span><br>    <span class="hljs-comment">//ResponseEntity表示响应实体:要下载的文件是通过响应体响应给客户端的</span><br>    <span class="hljs-comment">//创建添加响应头</span><br>    MultiValueMap&lt;String, String&gt; headers = <span class="hljs-keyword">new</span> HttpHeaders();<br>    <span class="hljs-comment">//获取要下载的文件的mime-type,设置Content-Type响应头</span><br>    String contentType = servletContext.getMimeType(fileName);<br>    headers.add(<span class="hljs-string">&quot;Content-Type&quot;</span>,contentType);<br><br>    <span class="hljs-comment">//Content-Disposition:响应头是指示客户端下载内容</span><br>    headers.add(<span class="hljs-string">&quot;Content-Disposition&quot;</span>,<span class="hljs-string">&quot;attachment;filename=&quot;</span>+fileName);<br><br>    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> ResponseEntity&lt;&gt;(buffer, headers,HttpStatus.OK);<br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="3-典型应用场景举例"><a href="#3-典型应用场景举例" class="headerlink" title="3. 典型应用场景举例"></a>3. 典型应用场景举例</h3><p>我们目前实现的是一个较为简单的下载，可以用在下面的一些场合：</p>
<ul>
<li>零星小文件下载</li>
<li>将系统内部的数据导出为 Excel、PDF 等格式，然后以下载的方式返回给用户</li>
</ul>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/springMVC/">springMVC</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/springMVC/">springMVC</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客目前大部分文章都是参考尚硅谷或者马士兵教育的学习资料！<a href="http://www.atguigu.com/" rel="nofollow noopener"官网地址！</a> 
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2021/12/16/Linux-01/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Linux-入门</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2021/12/13/springMVC-04/">
                        <span class="hidden-mobile">springMVC-04</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
              <!-- Comments -->
              <article class="comments" id="comments" lazyload>
                
                  
                
                

              </article>
            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">

  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
	<!--《添加网站运行时间 -->
<br/>

<span id="timeDate">载入天数...</span><span id="times">载入时分秒...</span>
<script>
var now = new Date(); 

function createtime() {
    //此处修改你的建站时间或者网站上线时间
    var grt = new Date('11/02/2021 21:39:00');
    now.setTime(now.getTime() + 250);
    days = (now - grt) / 1000 / 60 / 60 / 24;

    dnum = Math.floor(days);
    hours = (now - grt) / 1000 / 60 / 60 - (24 * dnum);
    hnum = Math.floor(hours);
    if (String(hnum).length == 1) {
        hnum = "0" + hnum;
    }
    minutes = (now - grt) / 1000 / 60 - (24 * 60 * dnum) - (60 * hnum);
    mnum = Math.floor(minutes);
    if (String(mnum).length == 1) {
        mnum = "0" + mnum;
    }
    seconds = (now - grt) / 1000 - (24 * 60 * 60 * dnum) - (60 * 60 * hnum) - (60 * mnum);
    snum = Math.round(seconds);
    if (String(snum).length == 1) {
        snum = "0" + snum;
    }
    document.getElementById("timeDate").innerHTML = " 本站已各种夹缝中安全运行 " + dnum + " 天 ";
    document.getElementById("times").innerHTML = hnum + " 小时 " + mnum + " 分 " + snum + " 秒";
}
setInterval("createtime()", 250);
</script>

<!-- 添加网站运行时间》-->
  </div>
  
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
      typing(title)
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
